<template>
  <div class="content-container">
    <!-- 标题区域 -->
    <div class="content-header">
      <div class="header-left">
        <h1 class="page-title">内容管理</h1>
        <p class="page-subtitle">管理您的所有内容资源</p>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button icon="el-icon-download">导出</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="showAddContentDialog">新建内容</el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 过滤和搜索区域 -->
    <div class="filter-section">
      <div class="filter-container">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-select v-model="contentType" placeholder="内容类型" class="filter-item">
              <el-option v-for="item in contentTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-select v-model="contentStatus" placeholder="状态" class="filter-item">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="filter-item" />
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-input v-model="searchKeyword" placeholder="搜索内容..." prefix-icon="el-icon-search" class="filter-item" />
          </el-col>
        </el-row>
        <el-row class="filter-buttons">
          <el-button type="primary" plain @click="handleFilter">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-row>
      </div>
    </div>
    
    <!-- 内容列表区域 -->
    <div class="content-section">
      <!-- 切换视图按钮 -->
      <div class="view-toggle">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="list"><i class="el-icon-menu"></i> 列表视图</el-radio-button>
          <el-radio-button label="grid"><i class="el-icon-s-grid"></i> 网格视图</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 列表视图 -->
      <div v-if="viewMode === 'list'" class="list-view">
        <el-table :data="contentList" stripe border style="width: 100%" v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="scope">
              <div class="content-title-cell">
                <el-image :src="scope.row.thumbnail" :preview-src-list="[scope.row.thumbnail]" class="content-thumbnail" fit="cover" />
                <div class="content-info">
                  <div class="content-title">{{ scope.row.title }}</div>
                  <div class="content-meta">{{ scope.row.type }} • {{ scope.row.createTime }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" width="120" />
          <el-table-column prop="category" label="分类" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="viewCount" label="浏览量" width="100" sortable />
          <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="text" size="small" @click="handlePreview(scope.row)">预览</el-button>
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-dropdown size="small" trigger="click">
                <el-button type="text" size="small">
                  更多<i class="el-icon-arrow-down"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handlePublish(scope.row)">发布</el-dropdown-item>
                    <el-dropdown-item @click="handleCopy(scope.row)">复制</el-dropdown-item>
                    <el-dropdown-item @click="handleMove(scope.row)">移动</el-dropdown-item>
                    <el-dropdown-item divided @click="handleDelete(scope.row)" class="text-danger">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="grid-view">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in contentList" :key="item.id">
            <div class="content-card">
              <div class="card-cover">
                <el-image :src="item.thumbnail" fit="cover" class="card-image" />
                <div class="card-badges">
                  <el-tag size="small" :type="getStatusType(item.status)">{{ item.status }}</el-tag>
                </div>
                <div class="card-actions">
                  <el-button-group>
                    <el-button size="small" circle icon="el-icon-view" @click="handlePreview(item)" />
                    <el-button size="small" circle icon="el-icon-edit" @click="handleEdit(item)" />
                    <el-button size="small" circle icon="el-icon-delete" @click="handleDelete(item)" />
                  </el-button-group>
                </div>
              </div>
              <div class="card-body">
                <h3 class="card-title" :title="item.title">{{ item.title }}</h3>
                <p class="card-meta">{{ item.type }} • {{ item.author }}</p>
                <p class="card-desc">{{ item.description }}</p>
                <div class="card-footer">
                  <span class="card-date">{{ item.updateTime }}</span>
                  <span class="card-views"><i class="el-icon-view"></i> {{ item.viewCount }}</span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建内容对话框 -->
    <el-dialog
      title="新建内容"
      v-model="dialogVisible"
      width="700px"
      :before-close="handleDialogClose"
    >
      <el-form :model="contentForm" :rules="formRules" ref="contentFormRef" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="contentForm.title" placeholder="请输入内容标题" />
        </el-form-item>
        <el-form-item label="内容类型" prop="type">
          <el-select v-model="contentForm.type" placeholder="选择内容类型" style="width: 100%">
            <el-option v-for="item in contentTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-cascader
            v-model="contentForm.category"
            :options="categoryOptions"
            placeholder="选择分类"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="封面图" prop="thumbnail">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="uploadThumbnail"
            :show-file-list="false"
            :before-upload="beforeThumbnailUpload"
          >
            <img v-if="contentForm.thumbnail" :src="contentForm.thumbnail" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <i class="el-icon-plus"></i>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="contentForm.description" :rows="3" placeholder="请输入内容描述" />
        </el-form-item>
        <el-form-item label="内容正文" prop="content">
          <div class="editor-placeholder">
            富文本编辑器区域
          </div>
        </el-form-item>
        <el-form-item label="标签">
          <el-tag
            v-for="tag in contentForm.tags"
            :key="tag"
            closable
            @close="handleRemoveTag(tag)"
            class="tag-item"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputTagVisible"
            ref="tagInputRef"
            v-model="inputTagValue"
            class="tag-input"
            size="small"
            @keyup.enter="handleInputTagConfirm"
            @blur="handleInputTagConfirm"
          />
          <el-button v-else size="small" @click="showTagInput" icon="el-icon-plus">添加标签</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="contentForm.status">
            <el-radio label="draft">草稿</el-radio>
            <el-radio label="published">发布</el-radio>
            <el-radio label="scheduled">定时发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="contentForm.status === 'scheduled'" label="发布时间" prop="publishTime">
          <el-date-picker v-model="contentForm.publishTime" type="datetime" placeholder="选择发布时间" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveContent">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';

// 视图模式
const viewMode = ref('list');

// 表格加载状态
const loading = ref(false);

// 筛选条件
const contentType = ref('');
const contentStatus = ref('');
const dateRange = ref([]);
const searchKeyword = ref('');

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框控制
const dialogVisible = ref(false);
const contentFormRef = ref(null);

// 标签输入
const inputTagVisible = ref(false);
const inputTagValue = ref('');
const tagInputRef = ref(null);

// 内容表单
const contentForm = reactive({
  title: '',
  type: '',
  category: [],
  thumbnail: '',
  description: '',
  content: '',
  tags: [],
  status: 'draft',
  publishTime: ''
});

// 表单验证规则
const formRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择内容类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入内容描述', trigger: 'blur' }],
  status: [{ required: true, message: '请选择内容状态', trigger: 'change' }]
};

// 选项数据
const contentTypeOptions = [
  { label: '全部类型', value: '' },
  { label: '文章', value: 'article' },
  { label: '新闻', value: 'news' },
  { label: '公告', value: 'announcement' },
  { label: '产品', value: 'product' },
  { label: '页面', value: 'page' }
];

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '待审核', value: 'pending' },
  { label: '已拒绝', value: 'rejected' },
  { label: '已归档', value: 'archived' }
];

const categoryOptions = [
  {
    value: 'product',
    label: '产品',
    children: [
      { value: 'hardware', label: '硬件产品' },
      { value: 'software', label: '软件产品' },
      { value: 'service', label: '服务产品' }
    ]
  },
  {
    value: 'news',
    label: '新闻',
    children: [
      { value: 'company', label: '公司新闻' },
      { value: 'industry', label: '行业动态' },
      { value: 'media', label: '媒体报道' }
    ]
  },
  {
    value: 'help',
    label: '帮助',
    children: [
      { value: 'guide', label: '使用指南' },
      { value: 'faq', label: '常见问题' },
      { value: 'support', label: '技术支持' }
    ]
  }
];

// 模拟内容列表数据
const contentList = ref([
  {
    id: 1001,
    title: '系统更新公告：版本2.5重大功能更新',
    type: '公告',
    author: '系统管理员',
    category: '系统公告',
    status: 'published',
    viewCount: 1253,
    updateTime: '2023-05-15 10:30',
    createTime: '2023-05-15',
    thumbnail: 'https://via.placeholder.com/100x60',
    description: '本次更新包含多项功能优化和bug修复，提升了系统整体性能和用户体验。'
  },
  {
    id: 1002,
    title: '如何使用内容管理系统高效管理您的文章',
    type: '文章',
    author: '内容编辑',
    category: '使用教程',
    status: 'draft',
    viewCount: 876,
    updateTime: '2023-05-12 15:45',
    createTime: '2023-05-10',
    thumbnail: 'https://via.placeholder.com/100x60',
    description: '详细介绍内容管理系统的各项功能和使用技巧，帮助您提高工作效率。'
  },
  {
    id: 1003,
    title: '产品介绍：智能数据分析平台',
    type: '产品',
    author: '产品经理',
    category: '产品介绍',
    status: 'pending',
    viewCount: 542,
    updateTime: '2023-05-08 09:20',
    createTime: '2023-05-07',
    thumbnail: 'https://via.placeholder.com/100x60',
    description: '智能数据分析平台是一款集数据收集、清洗、分析和可视化于一体的综合性解决方案。'
  },
  {
    id: 1004,
    title: '行业深度：人工智能在企业管理中的应用',
    type: '新闻',
    author: '行业分析师',
    category: '行业动态',
    status: 'published',
    viewCount: 1890,
    updateTime: '2023-05-05 14:10',
    createTime: '2023-05-04',
    thumbnail: 'https://via.placeholder.com/100x60',
    description: '人工智能技术正在深刻改变企业管理模式，本文深入分析了AI在企业中的实际应用场景。'
  },
  {
    id: 1005,
    title: '常见问题解答：账户安全与隐私保护',
    type: '页面',
    author: '安全专家',
    category: '帮助文档',
    status: 'published',
    viewCount: 763,
    updateTime: '2023-04-28 11:35',
    createTime: '2023-04-25',
    thumbnail: 'https://via.placeholder.com/100x60',
    description: '关于账户安全和隐私保护的常见问题解答，帮助用户保护个人信息和账户安全。'
  }
]);

// 生命周期钩子
onMounted(() => {
  fetchContentList();
});

// 获取内容列表数据
const fetchContentList = () => {
  loading.value = true;
  // 模拟API请求
  setTimeout(() => {
    total.value = 56; // 模拟总记录数
    loading.value = false;
  }, 500);
};

// 根据状态获取标签类型
const getStatusType = (status) => {
  const statusMap = {
    published: 'success',
    draft: 'info',
    pending: 'warning',
    rejected: 'danger',
    archived: 'info'
  };
  return statusMap[status] || 'info';
};

// 搜索和筛选处理
const handleFilter = () => {
  currentPage.value = 1;
  fetchContentList();
};

// 重置筛选条件
const resetFilter = () => {
  contentType.value = '';
  contentStatus.value = '';
  dateRange.value = [];
  searchKeyword.value = '';
  handleFilter();
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchContentList();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchContentList();
};

// 内容操作处理
const handlePreview = (row) => {
  console.log('预览内容', row);
};

const handleEdit = (row) => {
  console.log('编辑内容', row);
};

const handleDelete = (row) => {
  console.log('删除内容', row);
};

const handlePublish = (row) => {
  console.log('发布内容', row);
};

const handleCopy = (row) => {
  console.log('复制内容', row);
};

const handleMove = (row) => {
  console.log('移动内容', row);
};

// 对话框相关处理
const showAddContentDialog = () => {
  // 重置表单
  if (contentFormRef.value) {
    contentFormRef.value.resetFields();
  }
  contentForm.title = '';
  contentForm.type = '';
  contentForm.category = [];
  contentForm.thumbnail = '';
  contentForm.description = '';
  contentForm.content = '';
  contentForm.tags = [];
  contentForm.status = 'draft';
  contentForm.publishTime = '';
  
  dialogVisible.value = true;
};

const handleDialogClose = (done) => {
  done();
};

const saveContent = () => {
  contentFormRef.value.validate((valid) => {
    if (valid) {
      console.log('提交内容表单', contentForm);
      dialogVisible.value = false;
      // 这里应该调用API保存内容
    } else {
      return false;
    }
  });
};

// 上传相关处理
const beforeThumbnailUpload = (file) => {
  const isImage = file.type.indexOf('image/') === 0;
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    alert('上传封面图片只能是图片格式!');
  }
  if (!isLt2M) {
    alert('上传封面图片大小不能超过 2MB!');
  }
  return isImage && isLt2M;
};

const uploadThumbnail = (options) => {
  const { file } = options;
  // 模拟上传
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    contentForm.thumbnail = reader.result;
  };
};

// 标签处理
const showTagInput = () => {
  inputTagVisible.value = true;
  // 在下一个 DOM 更新循环后，聚焦输入框
  setTimeout(() => {
    tagInputRef.value.focus();
  });
};

const handleInputTagConfirm = () => {
  const inputValue = inputTagValue.value;
  if (inputValue && contentForm.tags.indexOf(inputValue) === -1) {
    contentForm.tags.push(inputValue);
  }
  inputTagVisible.value = false;
  inputTagValue.value = '';
};

const handleRemoveTag = (tag) => {
  contentForm.tags.splice(contentForm.tags.indexOf(tag), 1);
};
</script>

<style scoped>
.content-container {
  padding: 20px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: var(--dark-color);
}

.page-subtitle {
  color: #666;
  margin: 5px 0 0;
}

.filter-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: var(--card-shadow);
}

.filter-container {
  width: 100%;
}

.filter-item {
  width: 100%;
  margin-bottom: 15px;
}

.filter-buttons {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.content-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--card-shadow);
}

.view-toggle {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 列表视图样式 */
.content-title-cell {
  display: flex;
  align-items: center;
}

.content-thumbnail {
  width: 60px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.content-info {
  display: flex;
  flex-direction: column;
}

.content-title {
  font-weight: 500;
}

.content-meta {
  font-size: 12px;
  color: #999;
}

/* 网格视图样式 */
.grid-view {
  margin-top: 20px;
}

.content-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 20px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.content-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.card-cover {
  position: relative;
  height: 160px;
}

.card-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.card-badges {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}

.card-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.card-cover:hover .card-actions {
  opacity: 1;
}

.card-body {
  padding: 15px;
}

.card-title {
  margin: 0 0 10px;
  font-size: 16px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.card-meta {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.card-desc {
  font-size: 13px;
  color: #666;
  margin-bottom: 10px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
}

/* 分页容器 */
.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.avatar-uploader {
  width: 100%;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  text-align: center;
  padding: 10px 0;
}

.avatar-uploader:hover {
  border-color: var(--primary-color);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}

.avatar {
  width: 128px;
  height: 128px;
  display: block;
}

/* 富文本编辑器占位 */
.editor-placeholder {
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
}

/* 标签样式 */
.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 90px;
  margin-right: 8px;
  vertical-align: bottom;
}

/* 危险文本样式 */
.text-danger {
  color: #F56C6C;
}
</style> 